package com.tt.utils.wordUtils.utils;

import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;

import java.math.BigInteger;

public class TableUtils {

    /**
     * 水平合并单元格
     * @param table 表格对象
     * @param row 行索引
     * @param fromCol 起始列索引
     * @param toCol 结束列索引
     */
    public static void mergeCellsHorizontal(XWPFTable table, int row, int fromCol, int toCol) {
        for (int colIndex = fromCol; colIndex <= toCol; colIndex++) {
            XWPFTableCell cell = table.getRow(row).getCell(colIndex);
            if (cell == null) continue;

            CTTc ctTc = cell.getCTTc();
            CTTcPr tcPr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr();

            if (colIndex == fromCol) {
                // 起始单元格：设置跨列数量
                tcPr.addNewGridSpan().setVal(BigInteger.valueOf(toCol - fromCol + 1));
            } else {
                // 后续单元格：标记为已合并
                tcPr.addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * 创建跨多列的单元格
     * @param row 表格行
     * @param colSpan 跨列数量
     * @param text 单元格文本
     */
    public static void createMergedCell(XWPFTableRow row, int colSpan, String text) {
        // 先创建足够数量的单元格
        for (int i = 0; i < colSpan; i++) {
            row.addNewTableCell();
        }

        // 合并单元格
        XWPFTableCell firstCell = row.getCell(0);
        CTTc ctTc = firstCell.getCTTc();
        CTTcPr tcPr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr();
        tcPr.addNewGridSpan().setVal(BigInteger.valueOf(colSpan));

        // 设置文本
        firstCell.setText(text);

        // 标记后续单元格为已合并
        for (int i = 1; i < colSpan; i++) {
            XWPFTableCell cell = row.getCell(i);
            CTTc cellCtTc = cell.getCTTc();
            CTTcPr cellTcPr = cellCtTc.isSetTcPr() ? cellCtTc.getTcPr() : cellCtTc.addNewTcPr();
            cellTcPr.addNewHMerge().setVal(STMerge.CONTINUE);
        }
    }
}
